package com.ruoyi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.utils.SignUtils;
import com.ruoyi.domain.KuaiDi100Response;
import com.ruoyi.service.KuaiDi100Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class KuaiDi100Impl implements KuaiDi100Service {
    @Value("${kuaidi100.customer}")
    private String CUSTOMER;

    @Value("${kuaidi100.key}")
    private String KEY;

    /**
     * 查询快递流程
     *
     * @param com      快递公司编号
     * @param num      快递编号
     * @param resultv2 查询程度 1-4 [默认4: 详细查询]
     * @param phone 手机号[顺丰必填]
     * @return
     */
    @Override
    public KuaiDi100Response queryMaterialFlow(String com, String num, String resultv2, String phone) {
        try {
            QueryTrackReq queryTrackReq = new QueryTrackReq(); // 发送请求需要的参数
            QueryTrackParam queryTrackParam = new QueryTrackParam(); // 查询参数
            queryTrackParam.setCom(com);
            queryTrackParam.setNum(num);
            queryTrackParam.setPhone(phone);
            if (resultv2 != null) {
                queryTrackParam.setResultv2(resultv2);
            } else {
                queryTrackParam.setResultv2("4");
            }
            String param = new Gson().toJson(queryTrackParam);

            queryTrackReq.setParam(param);
            queryTrackReq.setCustomer(CUSTOMER);
            queryTrackReq.setSign(SignUtils.querySign(param, KEY, CUSTOMER));
            IBaseClient baseClient = new QueryTrack(); // 快递100自定义请求客户端
            final KuaiDi100Response result =
                    JSONObject.parseObject(baseClient.execute(queryTrackReq).getBody(), KuaiDi100Response.class);
            return result;
        } catch (Exception e) {
            log.error("快递接口错误{}",e);
            e.printStackTrace();
        }
        return null;
    }
    public KuaiDi100Response queryMaterialFlow(String com, String num, String resultv2) {
        return queryMaterialFlow(com, num, resultv2, null);
    }
    public KuaiDi100Response queryMaterialFlow(String com, String num) {
        return queryMaterialFlow(com, num, null, null);
    }
}
